
let countdownInterval;


function getWebSocketUrl(cb) {
  $.ajax({
    url: "/app/ai/audio/xunfei-iat-auth",
    success: function (res) {
      if (res.code) {
        startRecord.options.error(res.msg);
        return;
      }
      cb(res.data.id, res.data.auth);
    }
  });
}

function toBase64(buffer) {
  let binary = "";
  let bytes = new Uint8Array(buffer);
  let len = bytes.byteLength;
  for (let i = 0; i < len; i++) {
    binary += String.fromCharCode(bytes[i]);
  }
  return window.btoa(binary);
}

function renderResult(resultData) {
  // 识别结束
  let jsonData = JSON.parse(resultData);
  if (jsonData.data && jsonData.data.result) {
    let data = jsonData.data.result;
    let str = "";
    let ws = data.ws;
    for (let i = 0; i < ws.length; i++) {
      str = str + ws[i].cw[0].w;
    }
    if (data.pgs) {
      if (data.pgs === "apd") {
        startRecord.resultText = startRecord.resultTextTemp;
      }
      // 将结果存储在resultTextTemp中
      startRecord.resultTextTemp = startRecord.resultText + str;
    } else {
      startRecord.resultText = startRecord.resultText + str;
    }
    startRecord.result = startRecord.resultTextTemp || startRecord.resultText || "";
  }
  if (jsonData.code === 0 && jsonData.data.status === 2) {
    renderResult.iatWS.close();
  }
  if (jsonData.code !== 0) {
    renderResult.iatWS.close();
    console.error(jsonData);
  }
  return startRecord.result;
}

function connectWebSocket() {
  getWebSocketUrl(function (id, auth) {
    const websocketUrl = "wss://iat-api.xfyun.cn/v2/iat?" + auth
    if ("WebSocket" in window) {
      renderResult.iatWS = new WebSocket(websocketUrl);
    } else if ("MozWebSocket" in window) {
      renderResult.iatWS = new MozWebSocket(websocketUrl);
    } else {
      alert("浏览器不支持WebSocket");
      return;
    }
    renderResult.iatWS.onopen = (e) => {
      let params = {
        common: {
          app_id: id,
        },
        business: {
          language: startRecord.options.language || "zh_cn",
          domain: "iat",
          accent: "mandarin",
          vad_eos: 5000,
          dwa: "wpgs",
        },
        data: {
          status: 0,
          format: "audio/L16;rate=16000",
          encoding: "raw",
        },
      };
      renderResult.iatWS.send(JSON.stringify(params));
    };
    renderResult.iatWS.onmessage = (e) => {
      onProcess(renderResult(e.data));
    };
    renderResult.iatWS.onerror = (e) => {
      startRecord.recorder.stop();
      onStop();
    };
    renderResult.iatWS.onclose = (e) => {
      startRecord.recorder.stop();
      onComplete(startRecord.result);
      startRecord.result = '';
    };
  });
}

function onProcess(text) {
  startRecord.options.progress(text);
}

function onComplete(text) {
  startRecord.options.complete(text);
}
function onStart() {
  startRecord.options.start();
}

function onStop() {
  startRecord.options.stop();
}

export function startRecord(options) {
  startRecord.options = options;
  startRecord.startRecord = "";
  startRecord.resultText = "";
  startRecord.resultTextTemp = "";
  startRecord.frames = '';
  startRecord.recorder.start({
    sampleRate: 16000,
    frameSize: 1280,
  });
  console.log('start');
  connectWebSocket();
}

export function stopRecord() {
  startRecord.recorder.stop();
}

export function cancelRecord() {
  startRecord.result = '';
  stopRecord();
}

startRecord.recorder = new RecorderManager("/app/ai/js/xunfei/lib");
startRecord.recorder.onStart = () => {
  onStart();
}

startRecord.recorder.onFrameRecorded = ({ isLastFrame, frameBuffer }) => {
  if (renderResult.iatWS && renderResult.iatWS.readyState === renderResult.iatWS.OPEN) {
    if (startRecord.frames) {
      console.log('recorder frames.length=' + startRecord.frames.length);
      frameBuffer = startRecord.frames + frameBuffer;
      startRecord.frames = '';
    }
    renderResult.iatWS.send(
        JSON.stringify({
          data: {
            status: isLastFrame ? 2 : 1,
            format: "audio/L16;rate=16000",
            encoding: "raw",
            audio: toBase64(frameBuffer),
          },
        })
    );
  } else {
    startRecord.frames += frameBuffer;
  }
};
startRecord.recorder.onStop = () => {
  onStop();
};

